package com.chat.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 管理所有用户的websocket会话
 */
@Slf4j
@Component
public class WebSocketSessionManager {

    private final ConcurrentHashMap<Integer, WebSocketSession> sessionMap=new ConcurrentHashMap<>();

    public void addSession(Integer userId,WebSocketSession session){
        sessionMap.put(userId, session);
    }

    public void removeSession(Integer userId){
        sessionMap.remove(userId);
    }

    public WebSocketSession getSession(Integer userId){
        return sessionMap.get(userId);
    }

    public boolean isOnline(Integer userId) {
        WebSocketSession session = sessionMap.get(userId);
        return session != null && session.isOpen();
    }
}
